package com.zdp.mybatisplus.common;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author sesshomaru
 * @date 2019/12/3 11:49
 *
 * 数据源aop切换
 */
@Component
@Aspect
@Slf4j
@Order(-100)
public class DataSourceSwitchAspect {

    @Pointcut("execution(* com.zdp.mybatisplus.service.master..*.*(..))")
    public void masterAspect(){
    }

    @Pointcut("execution(* com.zdp.mybatisplus.service.slave..*.*(..))")
    public void slaveAspect(){
    }

    @Before("masterAspect()")
    public void master(JoinPoint joinPoint){
        setDataSource(joinPoint,DBTypeEnum.dbmaster);
    }

    @Before("slaveAspect()")
    public void slave(JoinPoint joinPoint){
        setDataSource(joinPoint,DBTypeEnum.dbslave);
    }

    private void setDataSource(JoinPoint joinpoint, DBTypeEnum dbTypeEnum){
        String dbType = DbContextHolder.getDbType();
        MethodSignature methodSignature = (MethodSignature)joinpoint.getSignature();
        DataSourceSwitch dataSourceSwitch = methodSignature.getMethod().getAnnotation(DataSourceSwitch.class);
        if(Objects.isNull(dataSourceSwitch) || Objects.isNull(dataSourceSwitch.value())){
            DbContextHolder.setDbType(dbTypeEnum);
            log.info("切换到" + dbTypeEnum.getValue() + " 数据源...");
        } else {
            log.info("根据注解来切换数据源,注解值为:" + dataSourceSwitch.value());
            switch (dataSourceSwitch.value().getValue()){
                case "master":
                    DbContextHolder.setDbType(DBTypeEnum.dbmaster);
                    log.info("切换到 master 数据源...");
                    break;
                case "slave":
                    DbContextHolder.setDbType(DBTypeEnum.dbslave);
                    log.info("切换到 slave 数据源...");
                    break;
                default:
                    DbContextHolder.setDbType(dbTypeEnum);
                    log.info("切换到 " + dbTypeEnum.getValue() + " 数据源...");
            }
        }

    }
}
